#!/usr/bin/env python
# encoding:UTF-8
import urllib
import sys
import time
import requests
import ossupload
from model import *
import xml.dom.minidom
import os

reload(sys)
sys.setdefaultencoding("UTF-8")


def downloadImage(imageid, dir, filename):
    url = "http://s.xingbook.com/huiben/" + imageid + ".jpg"
    if (not os.path.exists(dir)):
        os.mkdir(dir)
    filename = dir + '/' + str(filename) + ".jpg"
    conn = urllib.urlopen(url)
    f = open(filename, 'wb')
    f.write(conn.read())
    f.close()


def uploadImage(imageid):
    url = "http://s.xingbook.com/huiben/" + imageid + ".jpg"
    return ossupload(url)


def parsebookweb(bookid):
    url = "http://app2.xingbook.com/r/xq.do?t=112&i=" + bookid
    data = urllib.urlopen(url).read().encode("UTF-8")
    dom = xml.dom.minidom.parseString(data)

    imgids = []
    # 得到文档元素对象
    root = dom.documentElement
    imginfo = root.getElementsByTagName("q")[0].childNodes[0].data
    imginfo = imginfo.split("`")

    for id in imginfo:
        if len(id) == 0 or id.isdigit():
            continue
        imgids.append(id);

    return imgids


def downloadbook(bookid, dir):
    downloadImage(bookid, dir, "cover")
    imageids = parsebookweb(bookid)
    for id in imageids:
        downloadImage(id, dir, imageids.index(id))


def uploadbook(bookname, bookid):
    try:


        pos = bookname.find('(')
        if pos!= -1:
            bookname = bookname[0:pos]
        book = Book(bookname, '', 0)
        if book.find():
            return
        url = "http://s.xingbook.com/huiben/" + bookid + ".jpg"
        cover = ossupload.upload2oos(url)
        book.cover = cover
        book.pics =[]

        imageids = parsebookweb(bookid)
        for id in imageids:
            url = "http://s.xingbook.com/huiben/" + id + ".jpg"
            ossname = ossupload.upload2oos(url)
            pic = Pic(ossname, imageids.index(id))
            book.pics.append(pic)
        book.status = 1
        book.add();
    except Exception , e:
        print e


